package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gulimall
 * @description: 统一处理controller中的所有异常
 * @author: YuWenYi
 * @create: 2021-06-04 18:54
 **/


@Slf4j
//@ResponseBody
//@ControllerAdvice()
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常{},异常类型为{}",e.getMessage(),e.getClass());

        BindingResult result = e.getBindingResult();  //通过这个Exception去获取BindingResult
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            result.getFieldErrors().forEach((field) -> {
                String message = field.getDefaultMessage();
                String fieldName = field.getField();
                map.put(fieldName, message);
            });
        }
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    //兜底的异常处理方法
    @ExceptionHandler(value = Throwable.class)
    public R handleAllException(Throwable t){
        log.error("错误为:",t);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
